import 'package:flutter/material.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/core/providers/pages/home/news_model.dart';
import 'package:mall/core/providers/pages/home/news_query_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/home/news_detail_page.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class NewsItemPage extends StatelessWidget {
  final String linkType;
  final String title;

  NewsItemPage({
    Key key,
    @required this.linkType,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<NewsModel, NewsQueryModel>(
      create: (context) => NewsQueryModel(
        context.read<Api>(),
        context.read<AppModel>().currentStoreId,
        linkType,
      ),
      update: (context, newsModel, model) => model..queryKey = newsModel.queryKey,
      child: Consumer<NewsQueryModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget(title: title);
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final String title;
  final RefreshController _refreshController = RefreshController();

  _SuccessWidget({
    Key key,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    NewsQueryModel model = Provider.of(context, listen: false);
    final list = model.list;
    final newsQuery = model.newsQuery;
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 16),
            height: 45,
            child: Text(
              title,
              style: TextStyle(fontSize: 15),
            ),
          ),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              child: ListView.separated(
                itemBuilder: (context, index) {
                  return _NewsItemWidget(link: list[index]);
                },
                separatorBuilder: (context, index) {
                  return Divider(height: 1);
                },
                itemCount: list.length,
              ),
              enablePullDown: false,
              enablePullUp: newsQuery.newsList.length == 10,
              onLoading: () => _onLoadData(context),
            ),
          ),
        ],
      ),
    );
  }

  void _onLoadData(BuildContext context) async {
    NewsQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _NewsItemWidget extends StatelessWidget {
  final Link link;

  _NewsItemWidget({
    Key key,
    this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: InkWell(
        child: Container(
          padding: EdgeInsets.all(8),
          child: Row(
            children: <Widget>[
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: ImageNetwork(
                  url: '${link.image}',
                  width: 68,
                  height: 68,
                ),
              ),
              Expanded(
                child: Container(
                  height: 60,
                  margin: EdgeInsets.only(left: 8),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        link.title,
                        style: TextStyle(fontSize: 16),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                      ),
                      Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              link.creatorName ?? '--',
                              style: TextStyle(color: Colors.grey, fontSize: 12),
                            ),
                          ),
                          Text(
                            link.createTime ?? '--:--:--',
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        onTap: () {
          _onItemClicked(context);
        },
      ),
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(NewsDetailPage.routeName, arguments: link);
  }
}
